<?php
class DataHelper
{
    public static function getStates($locale=null)
    {
        if ($locale === null || empty($locale))
            $locale=Yii::app()->getLocale()->Id;
        
        if (strpos($locale, '_'))
        {
            list(,$locale) = explode('_', $locale);
        }
        $states = array();
        $states['es'] =
        $states['us'] = array(
            'AL'=>"Alabama",
            'AK'=>"Alaska",  
            'AZ'=>"Arizona",  
            'AR'=>"Arkansas",  
            'CA'=>"California",  
            'CO'=>"Colorado",  
            'CT'=>"Connecticut",  
            'DE'=>"Delaware",  
            'DC'=>"District Of Columbia",  
            'FL'=>"Florida",  
            'GA'=>"Georgia",  
            'HI'=>"Hawaii",  
            'ID'=>"Idaho",  
            'IL'=>"Illinois",  
            'IN'=>"Indiana",  
            'IA'=>"Iowa",  
            'KS'=>"Kansas",  
            'KY'=>"Kentucky",  
            'LA'=>"Louisiana",  
            'ME'=>"Maine",  
            'MD'=>"Maryland",  
            'MA'=>"Massachusetts",  
            'MI'=>"Michigan",  
            'MN'=>"Minnesota",  
            'MS'=>"Mississippi",  
            'MO'=>"Missouri",  
            'MT'=>"Montana",
            'NE'=>"Nebraska",
            'NV'=>"Nevada",
            'NH'=>"New Hampshire",
            'NJ'=>"New Jersey",
            'NM'=>"New Mexico",
            'NY'=>"New York",
            'NC'=>"North Carolina",
            'ND'=>"North Dakota",
            'OH'=>"Ohio",  
            'OK'=>"Oklahoma",  
            'OR'=>"Oregon",  
            'PA'=>"Pennsylvania",  
            'RI'=>"Rhode Island",  
            'SC'=>"South Carolina",  
            'SD'=>"South Dakota",
            'TN'=>"Tennessee",  
            'TX'=>"Texas",  
            'UT'=>"Utah",  
            'VT'=>"Vermont",  
            'VA'=>"Virginia",  
            'WA'=>"Washington",  
            'WV'=>"West Virginia",  
            'WI'=>"Wisconsin",  
            'WY'=>"Wyoming",
        );
        $states['ca'] = array(
            'AB'=>'Alberta',
            'BC'=>'British Columbia',
            'MB'=>'Manitoba',
            'NB'=>'New Brunswick',
            'NF'=>'Newfoundland',
            'NL'=>'Labrador',
            'NS'=>'Nova Scotia',
            'NT'=>'Northwest Territories',
            'NU'=>'Nunavut',
            'ON'=>'Ontario',
            'ON11'=>'Ontario - Stormont',
            'ON12'=>'Ontario - Dundas',
            'ON13'=>'Ontario - Glengarry',
            'ON14'=>'Ontario - Prescott',
            'ON15'=>'Ontario - Russell',
            'ON16'=>'Ontario - Ottawa-Carleton',
            'ON17'=>'Ontario - Leeds',
            'ON18'=>'Ontario - Grenville,Lanark',
            'ON19'=>'Ontario - Lanark',
            'ON21'=>'Ontario - Thunder Bay',
            'ON22'=>'Ontario - Rainy River',
            'ON23'=>'Ontario - Kenora',
            'ON3'=>'Ontario - All Other Regions',
            'PE'=>'Prince Edward Island',
            'QC'=>'Quebec',
            'SK'=>'Saskatchewan',
            'YT'=>'Yukon Territory',
        );
        
        return isset($states[$locale]) ? $states[$locale] : array();
    }
    
    const TITLE_MR = 1, TITLE_MRS = 2, TITLE_MS = 3, TITLE_MISS = 4;
    
    public function getTitles()
    {
        return array(
            self::TITLE_MR => 'Mr.',
            self::TITLE_MRS => 'Mrs.',
            self::TITLE_MS => 'Ms.',
            self::TITLE_MISS => 'Miss.',
        );
    }
    
    public static function normalizeArray2String($data, $delimiter = ', ')
    {
        $return = '';
        if (is_array($data) && count($data))
            $return = implode($delimiter, $data);
        return $return;
    }
    
    public static function normalizeString2Array($data, $delimiter = ',')
    {
        $return = array();
        if (empty($data) === false)
        {
            $return = explode($delimiter, $data);
            if (is_array($return))
                $return = array_map('trim', $return);
        }
        return is_array($return) ? $return : array();
    }
    
    public function getPhonePattern()
    {
        //detect pattern for zip by language
        switch(Yii::app()->language)
        {
            case 'fr_ca':
                $pattern = '/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/';
                break;
            case 'en_us':
            default:                
                $pattern = '/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/';
                break;
        }
        return $pattern;
    }
    
    public function getZipPattern()
    {
        //detect pattern for zip by language
        switch(Yii::app()->language)
        {
            case 'en_ca':
            case 'fr_ca':
                $pattern = '/^[a-zA-Z]{1}[0-9]{1}[a-zA-Z]{1}(\-|\s)?[0-9]{1}[a-zA-Z]{1}[0-9]{1}$/';
                break;
            case 'en_us':
            default:                
                $pattern = '/^[0-9]{3,5}$/';
                break;
        }
        return $pattern;
    }
    
    public function getPurchDatePattern()
    {
        //detect pattern for zip by language
        switch(Yii::app()->language)
        {
            case 'fr_ca':
                $pattern = '/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/';
                break;
            case 'en_us':
            default:                
                $pattern = '/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/';
                break;
        }
        return $pattern;
    }
    
    public function getPurchDateFormat()
    {
        //detect pattern for zip by language
        switch(Yii::app()->language)
        {
            case 'fr_ca':
                $format = 'yyyy-MM-dd';
                break;
            case 'en_us':
            default:                
                $format = 'yyyy-MM-dd';
                break;
        }
        return $format;
    }
    
    /**
    * @param string $input
    * @param int $numWords
    * @param mixed $restoreTags false|auto|purifier
    * 
    * @return string
    */
    public static function truncateWords($input, $numWords=50, $restoreTags='auto')
    {
        if (preg_match("/(\S+\s*){0,$numWords}/", $input, $matches))
        {
            $shortDesc = trim($matches[0]);
            switch ($restoreTags)
            {
                case 'auto':
                    $shortDesc = self::restoreTags($shortDesc);
                    break;
                case 'purifier':
                    $purifier = new CHtmlPurifier();
                    $shortDesc = $purifier->purify($shortDesc);
                    break;
            }
        }
        else
            $shortDesc = $input;
        return $shortDesc;
    }
    
    public static function restoreTags($input)
    {
        $opened = array();

        // loop through opened and closed tags in order
        if(preg_match_all("/<(\/?[a-z]+)>?/i", $input, $matches)) {
            foreach($matches[1] as $tag) {
                if(preg_match("/^[a-z]+$/i", $tag, $regs)) {
                    // a tag has been opened
                    if(strtolower($regs[0]) != 'br') $opened[] = $regs[0];
                } elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) {
                    // a tag has been closed
                    unset($opened[array_pop(array_keys($opened, $regs[1]))]);
                }
            }
        }

        // close tags that are still open
        if($opened) {
            $tagstoclose = array_reverse($opened);
            foreach($tagstoclose as $tag) $input .= "</$tag>";
        }

        return $input;
    }
    
    public static function getInterval($timestamp, $granularity = 2)
    {
        $seconds = time() - $timestamp;
        $units = array(
//            '1 năm|:count năm' => 31536000,
//            '1 tuần|:count tuần' => 604800,
//            '1 day|:count days' => 86400,
            '1 hour|:count hours' => 3600,
            '1 minute|:count minutes' => 60,
            '1 second|:count seconds' => 1);
        $output = '';
        if ($seconds < 86400) {
            foreach ($units as $key => $value) {
                $key = explode('|', $key);
                if ($seconds >= $value) {
                    $count = floor($seconds / $value);
                    $output .= ($output ? ' ' : '');
                    if ($count == 1) {
                        $output .= $key[0];
                    } else {
                        $output .= str_replace(':count', $count, $key[1]);
                    }
                    $seconds %= $value;
                    $granularity--;
                }
                if ($granularity == 0) {
                    break;
                }
            }
            if ($output)
                $output .= ' ago';
            else
                $output = '0 second';
        } else {
            if (date('Y', $timestamp) == date('Y'))
            {
                $output = Yii::app()->getDateFormatter()->format("dd MMM", $timestamp);
            }
            else
            {
                $output = Yii::app()->getDateFormatter()->format("dd MMM yy", $timestamp);
            }
        }

        return $output ? $output : '0 second';
    }
}